package com.kuzufang.modules.mine;

import android.app.DatePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jph.takephoto.app.TakePhoto;
import com.jph.takephoto.app.TakePhotoImpl;
import com.jph.takephoto.compress.CompressConfig;
import com.jph.takephoto.model.CropOptions;
import com.jph.takephoto.model.InvokeParam;
import com.jph.takephoto.model.TContextWrap;
import com.jph.takephoto.model.TResult;
import com.jph.takephoto.permission.InvokeListener;
import com.jph.takephoto.permission.PermissionManager;
import com.jph.takephoto.permission.TakePhotoInvocationHandler;
import com.kuzufang.R;
import com.kuzufang.base.BaseActivity;
import com.kuzufang.modules.imageutil.ImageHandler;

import java.io.File;
import java.util.Calendar;

/**
 * Created by songyuanjin on 2017/11/21.
 */

public class EditUserActivity extends BaseActivity implements View.OnClickListener, TakePhoto.TakeResultListener, InvokeListener {
    private InvokeParam invokeParam;

    private Toolbar mToolBar;
    private RelativeLayout rlPortrait;
    private RelativeLayout rlNick;
    private RelativeLayout rlSex;
    private RelativeLayout rlBirthday;
    private RelativeLayout rlWork;
    private RelativeLayout rlHome;
    private RelativeLayout rlWechat;
    private RelativeLayout rlPassword;

    private ImageView ivPortrait;

    private TextView tvNick;
    private TextView tvSex;
    private TextView tvBirthday;
    private TextView tvWork;
    private TextView tvHome;
    private TextView tvWechat;

    private Calendar calendar;
    private int year, month, day;


    //TakePhoto
    private TakePhoto takePhoto;
    private CropOptions cropOptions;  //裁剪参数
    private CompressConfig compressConfig;  //压缩参数
    private Uri imageUri;  //图片保存路径

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        getTakePhoto().onCreate(savedInstanceState);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_user);

        mToolBar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(mToolBar);

        initView();
        configPhoto();

    }

    private void initView() {
        rlPortrait = (RelativeLayout) findViewById(R.id.rl_portrait);
        rlNick = (RelativeLayout) findViewById(R.id.rl_nick);
        rlSex = (RelativeLayout) findViewById(R.id.rl_sex);
        rlBirthday = (RelativeLayout) findViewById(R.id.rl_birthday);
        rlWork = (RelativeLayout) findViewById(R.id.rl_work);
        rlHome = (RelativeLayout) findViewById(R.id.rl_home);
        rlWechat = (RelativeLayout) findViewById(R.id.rl_wechat);
        rlPassword = (RelativeLayout) findViewById(R.id.rl_password);

        tvSex = (TextView) findViewById(R.id.tv_sex);
        tvBirthday = (TextView) findViewById(R.id.tv_birthday);

        ivPortrait = (ImageView) findViewById(R.id.iv_portrait);

        rlPortrait.setOnClickListener(this);
        rlSex.setOnClickListener(this);
        rlBirthday.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_portrait:
                changePortrait();
                break;
            case R.id.rl_nick:
                break;
            case R.id.rl_sex:
                setSex();
                break;
            case R.id.rl_birthday:
                setBirthday();
                break;
            case R.id.rl_work:
                break;
            case R.id.rl_home:
                break;
            case R.id.rl_wechat:
                break;
            case R.id.rl_password:
                break;

        }
    }

    private void changePortrait() {
        CharSequence[] chars = new CharSequence[]{"拍照", "相册选择", "取消"};
        new AlertDialog.Builder(this).setTitle("更换头像").setItems(chars, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                switch (which) {
                    case 0:
                        imageUri = getImageCropUri();
                        //拍照并裁剪
                        takePhoto.onPickFromCaptureWithCrop(imageUri, cropOptions);
                        break;
                    case 1:
                        imageUri = getImageCropUri();
                        //从相册中选取图片并裁剪
                        takePhoto.onPickFromGalleryWithCrop(imageUri, cropOptions);
                        break;
                }
            }
        }).create().show();
    }

    private void setSex() {
        final CharSequence[] chars = new CharSequence[]{"男", "女", "保密"};
        new AlertDialog.Builder(this).setTitle("性别").setItems(chars, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                tvSex.setText(chars[which]);
            }
        }).create().show();
    }

    private void setBirthday() {
        calendar = Calendar.getInstance();
        year = calendar.get(Calendar.YEAR);       //获取年月日时分秒
        month = calendar.get(Calendar.MONTH);   //获取到的月份是从0开始计数
        day = calendar.get(Calendar.DAY_OF_MONTH);
        DatePickerDialog datePickerDialog = new DatePickerDialog(EditUserActivity.this, 0, listener, year, month, day);
        datePickerDialog.show();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.search_confirm, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        super.onOptionsItemSelected(item);
        switch (item.getItemId()) {
            case R.id.search_confirm:
                Toast.makeText(this, "Confirm", Toast.LENGTH_SHORT).show();
                break;
            case android.R.id.home:
                onBackPressed();
        }
        return true;
    }

    DatePickerDialog.OnDateSetListener listener = new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker arg0, int year, int month, int day) {
            tvBirthday.setText(year + "-" + (++month) + "-" + day);      //将选择的日期显示到TextView中,因为之前获取month直接使用，所以不需要+1，这个地方需要显示，所以+1
        }
    };

    /**
     * 获取TakePhoto实例
     *
     * @return
     */
    public TakePhoto getTakePhoto() {
        if (takePhoto == null) {
            takePhoto = (TakePhoto) TakePhotoInvocationHandler.of(this).bind(new TakePhotoImpl(this, this));
        }
        return takePhoto;
    }

    @Override
    public void takeSuccess(TResult result) {
        String iconPath = result.getImage().getOriginalPath();
        ImageHandler.getImageLoader().load(EditUserActivity.this, new File(iconPath), ivPortrait);
    }

    @Override
    public void takeFail(TResult result, String msg) {

    }

    @Override
    public void takeCancel() {

    }

    @Override
    public PermissionManager.TPermissionType invoke(InvokeParam invokeParam) {
        PermissionManager.TPermissionType type = PermissionManager.checkPermission(TContextWrap.of(this), invokeParam.getMethod());
        if (PermissionManager.TPermissionType.WAIT.equals(type)) {
            this.invokeParam = invokeParam;
        }
        return type;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.TPermissionType type = PermissionManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.handlePermissionsResult(this, type, invokeParam, this);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        getTakePhoto().onSaveInstanceState(outState);
        super.onSaveInstanceState(outState);
    }

    private void configPhoto() {
        getTakePhoto();
        cropOptions = new CropOptions.Builder().setAspectX(1).setAspectY(1).setWithOwnCrop(false).create();
        compressConfig = new CompressConfig.Builder().setMaxSize(50 * 1024).setMaxPixel(800).create();
        takePhoto.onEnableCompress(compressConfig, true);  //设置为需要压缩
    }

    private Uri getImageCropUri() {
        File file = new File(Environment.getExternalStorageDirectory(), "/temp/" + System.currentTimeMillis() + ".jpg");
        if (!file.getParentFile().exists()) file.getParentFile().mkdirs();
        return Uri.fromFile(file);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        getTakePhoto().onActivityResult(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
    }
}
